package com.netease.nim.demo.common.media.watch.image;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.netease.nim.demo.common.activity.TActionBarActivity;
import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog;
import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog.onSeparateItemClickListener;
import com.netease.nim.demo.common.ui.imageview.ImageGestureListener;
import com.netease.nim.demo.common.ui.imageview.MultiTouchZoomableImageView;
import com.netease.nim.demo.common.util.C;
import com.netease.nim.demo.common.util.media.BitmapDecoder;
import com.netease.nim.demo.common.util.media.ImageUtil;
import com.netease.nim.demo.session.model.MsgListItem;
import com.netease.nim.demo.util.AttachmentStore;
import com.netease.nim.demo.util.storage.StorageUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.constant.AttachStatusEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw.activity.NewInteractionCreateTeamChMActivity;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.widget.touch_imageview.ExtendedViewPager;
import com.shwread.android.ui.widget.touch_imageview.TouchImageView;

import java.util.ArrayList;
import java.util.List;

import logic.constants.DefaultConsts;
import logic.util.FileUtil;


/**
 * 查看聊天消息原图
 * Created by huangjun on 2015/3/6.
 */
public class WatchMessagePictureActivity
        extends
        TActionBarActivity
        implements
        OnClickListener
{
	
	private static final String	INTENT_EXTRA_IMAGE = "INTENT_EXTRA_IMAGE";
												   
	private Handler				handler;
								
	private View				loadingLayout;
	protected CustomAlertDialog	alertDialog;
	private ExtendedViewPager	viewPager;
	private MyViewPagerAdapter	adapter;
	private List<MsgListItem>	msgListItems;
	private TextView			mCount;
	private RelativeLayout		titleLay;
	private Button				mBackBtn;
	private int					pos;
	private boolean				isShow			   = true;
	private Context				context;
	private int					comeInPosition	   = 0;					  //刚进来的position，从0开始
	private int					totalNumber;
	//	public static void start(Context context, IMMessage message) {
	//		Intent intent = new Intent();
	//		intent.putExtra(INTENT_EXTRA_IMAGE, message);
	//		intent.setClass(context, WatchMessagePictureActivity.class);
	//		context.startActivity(intent);
	//	}
	
	public static void start(Context context, ArrayList<MsgListItem> msgListItems, int pos) {
		Intent intent = new Intent();
		intent.putExtra(INTENT_EXTRA_IMAGE, msgListItems);
		intent.putExtra("pos", pos);
		intent.setClass(context, WatchMessagePictureActivity.class);
		context.startActivity(intent);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		onParseIntent();
		setContentView(R.layout.watch_picture_activity);
		findViews();
		adapter = new MyViewPagerAdapter();
		viewPager.setAdapter(adapter);
		viewPager.setCurrentItem(pos);
		viewPager.setOnPageChangeListener(new PageChangeListener());
		handler = new Handler();
		initListener();
		//		registerObservers(true);
		//		requestOriImage();
	}
	
	private void initListener() {
		viewPager.setOnClickListener(this);
		loadingLayout.setOnClickListener(this);
		mBackBtn.setOnClickListener(this);
	}
	
	@Override
	protected void onDestroy() {
		//		registerObservers(false);
		super.onDestroy();
	}
	
	private void onParseIntent() {
		this.msgListItems = (List<MsgListItem>) getIntent().getSerializableExtra(INTENT_EXTRA_IMAGE);
		this.pos = getIntent().getIntExtra("pos", -1);
		totalNumber = msgListItems.size();
		comeInPosition = pos;
	}
	
	private void hideDetail() {
		Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_out);
		titleLay.setAnimation(animationTop);
		animationTop.start();
		Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_out);
		animationBottom.start();
		titleLay.setVisibility(View.GONE);
		isShow = false;
	}
	
	/**
	 * 管理上下内容的显示
	 */
	private void detailManager() {
		if (isShow)
		{
			hideDetail();
		}
		else
		{
			showDetail();
		}
		
	}
	
	//显示图片细节，上下透明度
	private void showDetail() {
		titleLay.setVisibility(View.VISIBLE);
		//		introLay.setVisibility(View.VISIBLE);
		Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_in);
		titleLay.setAnimation(animationTop);
		animationTop.start();
		//		Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_in);
		//		introLay.setAnimation(animationBottom);
		//		animationBottom.start();
		isShow = true;
	}
	
	private void findViews() {
		titleLay = (RelativeLayout) findViewById(R.id.atlas_see_title_lay);
		mBackBtn = (Button) findViewById(R.id.atlas_see_title_back);
		mCount = (TextView) findViewById(R.id.atlas_see_title_count);
		alertDialog = new CustomAlertDialog(this);
		loadingLayout = findViewById(R.id.loading_layout);
		viewPager = (ExtendedViewPager) findViewById(R.id.atlas_see_vp);
		mCount.setText(comeInPosition + 1 + "/" + totalNumber);
	}
	
	private void requestOriImage(IMMessage msg, MultiTouchZoomableImageView ima) {
		if (isOriginImageHasDownloaded(msg))
		{
			onDownloadSuccess(msg, ima);
			return;
		}
		
		// async download original image
		onDownloadStart(msg, ima);
		NIMClient.getService(MsgService.class).downloadAttachment(msg, false);
	}
	
	private boolean isOriginImageHasDownloaded(final IMMessage message) {
		if (message.getAttachStatus() == AttachStatusEnum.transferred && !TextUtils.isEmpty(((ImageAttachment) message.getAttachment()).getPath())) { return true; }
		
		return false;
	}
	
	/**
	 * ******************************** 设置图片 *********************************
	 */
	
	private void setThumbnail(IMMessage msg, MultiTouchZoomableImageView ima) {
		String path = ((ImageAttachment) msg.getAttachment()).getThumbPath();
		if (!TextUtils.isEmpty(path))
		{
			Bitmap bitmap = BitmapDecoder.decodeSampledForDisplay(path);
			bitmap = ImageUtil.rotateBitmapInNeeded(path, bitmap);
			if (bitmap != null)
			{
				ima.setImageBitmap(bitmap);
				return;
			}
		}
		
		ima.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnLoading()));
	}
	
	private void setImageView(final IMMessage msg, final MultiTouchZoomableImageView ima) {
		String path = ((ImageAttachment) msg.getAttachment()).getPath();
		if (TextUtils.isEmpty(path))
		{
			ima.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnLoading()));
			return;
		}
		
		Bitmap bitmap = BitmapDecoder.decodeSampledForDisplay(path, false);
		bitmap = ImageUtil.rotateBitmapInNeeded(path, bitmap);
		if (bitmap == null)
		{
			Toast.makeText(this, R.string.picker_image_error, Toast.LENGTH_LONG).show();
			ima.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
		}
		else
		{
			ima.setImageBitmap(bitmap);
		}
	}
	
	private int getImageResOnLoading() {
		return R.drawable.sdk_share_dialog_thumb_default;
	}
	
	private int getImageResOnFailed() {
		return R.drawable.qr_code_no_found;
	}
	
	/**
	 * ********************************* 下载
	 * ****************************************
	 */
	
	//	private void registerObservers(boolean register) {
	//		NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(statusObserver, register);
	//	}
	//
	//	private Observer<IMMessage> statusObserver = new Observer<IMMessage>()
	//	                                           {
	//		                                           @Override
	//		                                           public void onEvent(IMMessage msg) {
	//			                                           if (!msg.isTheSame(message) || isDestroyedCompatible()) { return; }
	//
	//			                                           if (msg.getAttachStatus() == AttachStatusEnum.transferred && isOriginImageHasDownloaded(msg))
	//			                                           {
	//				                                           onDownloadSuccess(msg);
	//			                                           }
	//			                                           else if (msg.getAttachStatus() == AttachStatusEnum.fail)
	//			                                           {
	//				                                           onDownloadFailed();
	//			                                           }
	//		                                           }
	//	                                           };
	//
	private void onDownloadStart(final IMMessage msg, MultiTouchZoomableImageView ima) {
		setThumbnail(msg, ima);
		if (TextUtils.isEmpty(((ImageAttachment) msg.getAttachment()).getPath()))
		{
			loadingLayout.setVisibility(View.VISIBLE);
		}
		else
		{
			loadingLayout.setVisibility(View.GONE);
		}
		
	}
	
	private void onDownloadSuccess(final IMMessage msg, final MultiTouchZoomableImageView ima) {
		loadingLayout.setVisibility(View.GONE);
		handler.post(new Runnable()
		{
			
			@Override
			public void run() {
				setImageView(msg, ima);
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.atlas_see_vp:
				detailManager();
				break;
			case R.id.loading_layout:
				detailManager();
				break;
			case R.id.atlas_see_title_back:
				finish();
				break;
				
		}
	}
	//
	//	private void onDownloadFailed() {
	//		loadingLayout.setVisibility(View.GONE);
	//		image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
	//		Toast.makeText(this, R.string.download_picture_fail, Toast.LENGTH_LONG).show();
	//	}
	
	/**
	 * 适配器
	 */
	
	class MyViewPagerAdapter
	        extends
	        PagerAdapter
	{
		
		@Override
		public int getCount() {
			return msgListItems.size();
		}
		
		@Override
		public View instantiateItem(ViewGroup container, final int position) {
			final ViewHolder holder;
			View view = null;
			holder = new ViewHolder();
			final IMMessage message = msgListItems.get(position).getMessage();
			view = LayoutInflater.from(context).inflate(R.layout.atlas_see_item, viewPager, false);
			holder.loading_lay = (LinearLayout) view.findViewById(R.id.atlas_see_item_loading);
			holder.loadFail_lay = (LinearLayout) view.findViewById(R.id.atlas_see_item_loadfail);
			holder.img = (MultiTouchZoomableImageView) view.findViewById(R.id.watch_image_view);
			holder.img2 = (TouchImageView) view.findViewById(R.id.atlas_see_item_img);
			holder.img.setVisibility(View.VISIBLE);
			holder.img2.setVisibility(View.GONE);
			final String path = FileUtil.ImageSavePath();
			//			final String filename = new Md5FileNameGenerator().generate(imgList.get(position)) + ".PNG";
			//			final String dstPath = path + filename;
			NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(new Observer<IMMessage>()
			{
				@Override
				public void onEvent(IMMessage msg) {
					if (!msg.isTheSame(message) || isDestroyedCompatible()) { return; }
					
					if (msg.getAttachStatus() == AttachStatusEnum.transferred && isOriginImageHasDownloaded(msg))
					{
						onDownloadSuccess(msg, holder.img);
					}
					else if (msg.getAttachStatus() == AttachStatusEnum.fail)
					{
						onDownloadFailed(holder.img);
					}
				}
			}, true);
			requestOriImage(message, holder.img);
			onImageViewFound(holder.img, message);
			container.addView(view);
			return view;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
	}
	
	class ViewHolder
	{
		LinearLayout				loading_lay, loadFail_lay;
		MultiTouchZoomableImageView	img;
		TouchImageView				img2;
	}
	
	private void onDownloadFailed(MultiTouchZoomableImageView img) {
		loadingLayout.setVisibility(View.GONE);
		img.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
		Toast.makeText(this, R.string.download_picture_fail, Toast.LENGTH_LONG).show();
	}
	
	/**
	 * ***********************************图片点击事件********************************
	 * ***********
	 */
	
	// 设置图片点击事件
	protected void onImageViewFound(MultiTouchZoomableImageView imageView, final IMMessage msg) {
		imageView.setImageGestureListener(new ImageGestureListener()
		{
			
			@Override
			public void onImageGestureSingleTapConfirmed() {
				onImageViewTouched();
			}
			
			@Override
			public void onImageGestureLongPress() {
				showWatchPictureAction(msg);
			}
			
			@Override
			public void onImageGestureFlingDown() {
				finish();
			}
		});
	}
	
	// 图片单击
	protected void onImageViewTouched() {
		finish();
	}
	
	// 图片长按
	protected void showWatchPictureAction(final IMMessage msg) {
		if (alertDialog.isShowing())
		{
			alertDialog.dismiss();
			return;
		}
		alertDialog.clearData();
		String path = ((ImageAttachment) msg.getAttachment()).getThumbPath();
		//		if (TextUtils.isEmpty(path)) { return; }
		String title;
		if (!TextUtils.isEmpty(((ImageAttachment) msg.getAttachment()).getPath()) || TextUtils.isEmpty(path))
		{
			title = getString(R.string.save_to_device);
			alertDialog.addItem(title, new onSeparateItemClickListener()
			{
				
				@Override
				public void onClick() {
					savePicture(msg);
				}
			});
		}
		alertDialog.addItem("转发", new onSeparateItemClickListener()
		{
			@Override
			public void onClick() {
				//					Toast.makeText(WatchMessagePictureActivity.this, "转发", Toast.LENGTH_LONG).show();
				MsgListItem selectedItem = new MsgListItem(msg);
				Intent intent = new Intent(WatchMessagePictureActivity.this, NewInteractionCreateTeamChMActivity.class);
				intent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_FORWARD);
				intent.putExtra("message", selectedItem);
				startActivity(intent);
				finish();
			}
		});
		alertDialog.show();
	}
	
	// 保存图片
	public void savePicture(IMMessage msg) {
		ImageAttachment attachment = (ImageAttachment) msg.getAttachment();
		String path = attachment.getPath();
		if (TextUtils.isEmpty(path)) { return; }
		
		String srcFilename = attachment.getFileName();
		//默认jpg
		String extension = TextUtils.isEmpty(attachment.getExtension()) ? "jpg" : attachment.getExtension();
		srcFilename += ("." + extension);
		
		String picPath = StorageUtil.getSystemImagePath();
		String dstPath = picPath + srcFilename;
		if (AttachmentStore.copy(path, dstPath) != -1)
		{
			try
			{
				ContentValues values = new ContentValues(2);
				values.put(MediaStore.Images.Media.MIME_TYPE, C.MimeType.MIME_JPEG);
				values.put(MediaStore.Images.Media.DATA, dstPath);
				getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
				Toast.makeText(WatchMessagePictureActivity.this, getString(R.string.picture_save_to), Toast.LENGTH_LONG).show();
			}
			catch (Exception e)
			{
				// may be java.lang.UnsupportedOperationException
				Toast.makeText(WatchMessagePictureActivity.this, getString(R.string.picture_save_fail), Toast.LENGTH_LONG).show();
			}
		}
		else
		{
			Toast.makeText(WatchMessagePictureActivity.this, getString(R.string.picture_save_fail), Toast.LENGTH_LONG).show();
		}
	}
	
	/**
	 * ViewPager滑动监听器
	 */
	private class PageChangeListener
	        implements
	        ViewPager.OnPageChangeListener
	{
		//		private int curCount = comeInPosition;
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		
		@Override
		public void onPageSelected(int arg0) {
			comeInPosition = arg0;
			mCount.setText((comeInPosition + 1) + "/" + totalNumber);
		}
	}
}
